﻿using System.Collections.Generic;
using System.Data.SqlClient;
using InvestmentIntelligence.DB;
using InvestmentIntelligence.DbModel.Models;

namespace InvestmentIntelligence.Data.Repository.SqlImplementation
{
    public class AnalyticsIdeaToSecurityRepository : ISqlAnalyticsIdeaToSecurityRepository
    {
        private const int MergeTimeout = 300;
        private const string TableName = "[Analytics].[IdeaToSecurity]";
        
        public void Merge(IEnumerable<AnalyticsIdeaToSecurity> items)
        {
            using (var conn = IIPConnectionString.CreateSqlConnection())
            {
                conn.Open();
                var tempTableName = DbHelper.BulkCopyToTempTable(conn, TableName, items);
                Merge(conn, tempTableName);
            }
        }

        private static void Merge(SqlConnection conn, string tempTableName)
        {
            var sql = string.Format(@"
MERGE
	{0} i2s
USING
	{1} i2st
ON
	i2s.[IdeaId] = i2st.[IdeaId] AND i2s.[SecurityId] = i2st.[SecurityId]
WHEN NOT MATCHED THEN 
    INSERT VALUES ([IdeaId], [SecurityId])
OPTION (MAXDOP 1)
;
",
 TableName,
 tempTableName);
            var cmd = new SqlCommand(sql, conn) {CommandTimeout = MergeTimeout};
            cmd.ExecuteNonQuery();
        }

        public void Insert(IEnumerable<AnalyticsIdeaToSecurity> items)
        {
            using (var conn = IIPConnectionString.CreateSqlConnection())
            {
                conn.Open();
                var bi = new BulkCopy<AnalyticsIdeaToSecurity>(conn, null, TableName, items);
                bi.Execute();
            }
        }
    }
}
